package com.huluobo.a2203kotlinshopping.home

import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2203kotlinshopping.R
import com.huluobo.a2203kotlinshopping.adapter.HomeGoodsListAdapter
import com.huluobo.a2203kotlinshopping.adapter.HomeNavAdapter
import com.huluobo.a2203kotlinshopping.databinding.FragmentHomeBinding
import com.huluobo.a2203kotlinshopping.detail.DetailActivity
import com.huluobo.a2203kotlinshopping.utils.ImageUtils
import com.huluobo.base.bean.HomeGoodsBean
import com.huluobo.base.bean.HomeNavBean
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMFragment
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader

class HomeFragment : BaseMVVMFragment<FragmentHomeBinding, HomeViewModel>() {
    //商品的数据源
    private val goodsList = mutableListOf<HomeGoodsBean>()

    //商品的adapter
    private lateinit var homeGoodsListAdapter: HomeGoodsListAdapter

    //导航的数据源
    private val navList = mutableListOf<HomeNavBean>()

    //导航的adapter
    private lateinit var homeNavAdapter: HomeNavAdapter

    //banner的数据源
    private val bannerUrls = mutableListOf<String>()

    //上拉加载更多需要更新的currentPage
    private var currentPage = 1

    override fun getLayoutId(): Int = R.layout.fragment_home

    override fun getViewModel(): Class<HomeViewModel> = HomeViewModel::class.java

    override fun initData() {
        viewModel.getHomeGoodsList(0, currentPage, 10)
        viewModel.getHomeBanner()
        viewModel.getHomeNav()

        viewModel.getHomeGoodsListSuccess.observe(this) {
            if (it.code == 200) {
                //当currentPage等于1的时候,要么是初始化的状态,要么是下拉刷新的状态,需要重置list数据源
                if (currentPage == 1) {
                    goodsList.clear()
                }
                dataBinding.homeRefresh.finishRefresh()
                dataBinding.homeRefresh.finishLoadMore()
                goodsList.addAll(it.data)
                homeGoodsListAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getHomeGoodsListFailed.observe(this) {
            Log.i("TagA", "首页商品列表失败:$it")
        }

        viewModel.getHomeBannerSuccess.observe(this) {
            bannerUrls.clear()
            it.data.forEach { bannerBean ->
                bannerUrls.add(bannerBean.imagePath)
            }
            dataBinding.homeBanner.setImages(bannerUrls)
            dataBinding.homeBanner.start()
        }

        viewModel.getHomeBannerFailed.observe(this) {
            Log.i("TagA", "首页banner失败:$it")
        }

        viewModel.getHomeNavSuccess.observe(this) {
            if (it.code == 200) {
                navList.clear()
                navList.addAll(it.data[0].data!!)
                homeNavAdapter.notifyDataSetChanged()
            }
        }

        viewModel.getHomeNavFailed.observe(this) {
            Log.i("TagA", "首页导航失败:$it")
        }
    }

    override fun initView() {
        //初始化商品列表
        dataBinding.homeRv.layoutManager = GridLayoutManager(requireContext(), 2)
        homeGoodsListAdapter = HomeGoodsListAdapter(goodsList)
        dataBinding.homeRv.adapter = homeGoodsListAdapter
        homeGoodsListAdapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(requireContext(), DetailActivity::class.java)
            //传递商品id
            intent.putExtra(Const.PARAM_GOODS_ID, goodsList[position].id)
            startActivity(intent)
        }

        //初始化banner
        dataBinding.homeBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)//设置指示器风格
        dataBinding.homeBanner.setImageLoader(object : ImageLoader() {
            //设置banner的图片加载器
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                imageView.let {
                    if (context != null && path != null) {
                        ImageUtils.loadImage(context, path.toString(), it!!)
                    }
                }
            }
        })
        dataBinding.homeBanner.setDelayTime(2000)//设置banner播放时间
        dataBinding.homeBanner.setIndicatorGravity(BannerConfig.CENTER)

        //初始化刷新框架
        dataBinding.homeRefresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                //刷新时,判断一下当前刷新框架的状态,如果正在加载,则停止加载
                if (refreshLayout.isLoading) {
                    refreshLayout.finishLoadMore()
                }
                //刷新时,需要页面回到初始状态
                currentPage = 1
                viewModel.getHomeGoodsList(0, currentPage, 10)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (refreshLayout.isRefreshing) {
                    refreshLayout.finishRefresh()
                }
                currentPage += 1
                viewModel.getHomeGoodsList(0, currentPage, 10)
            }
        })

        //导航布局初始化
        dataBinding.homeNavRv.layoutManager = GridLayoutManager(context, 5)
        homeNavAdapter = HomeNavAdapter(navList)
        dataBinding.homeNavRv.adapter = homeNavAdapter
    }
}